<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Business  extends Home
{
  public function _initialize()
  {
    parent::_initialize();
    // 如果用助手调用多级模型 例如：路径：app\common\model\Business\Business
    $this->BusinessModel = model('Business.Business');
    $this->RegionModel = model('Region');
    $this->SubjectModel = model('Subject.Subject');
    $this->OrderModel = model('Subject.Order');
    $this->RecordModel = model('Business.Record'); //消费记录控制器
    $this->CommentModel = model('Subject.Comment'); //评论模型

  }

  // 个人中心
  public function index()
  {
    // 模板变量赋值
    $this->assign('status', 'business');
    return $this->view->fetch();
  }

  // 修改资料
  public function profile()
  {
    if ($this->request->isPost()) {
      $params = $this->request->param();
      $password = $this->request->param('password', '', 'trim');
      $code = $this->request->param('code', '', 'trim');

      // 查询是否用当前用户
      $businessinfo = $this->BusinessModel->find($this->LoginUser['id']);

      if (!$businessinfo) {
        $this->error('用户不存在');
      }

      $data = [
        'id' => $this->LoginUser['id'],
        'nickname' => $params['nickname'],
        'email' => $params['email'],
        'gender' => $params['gender'],
      ];

      // 判断是否修改地区
      if ($code) {
        $pathlist = $this->RegionModel->where('code', $code)->value('parentpath');

        if (!$pathlist) {
          $this->error('地区不存在');
        }

        $path = explode(',', $pathlist);

        $data['province'] = $path[0];
        $data['city'] = $path[1];
        $data['district'] = $path[2];
      }

      // 判断是否修改密码
      if ($password) {
        // 生成密码盐
        $salt = randstr();

        // 密码加密
        $password = md5($password . $salt);

        $data['password'] = $password;
      }

      // 判断是否修改头像
      if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
        $res = upload('avatar');

        if ($res['code'] == 0) {
          $this->error($res['msg']);
        }

        $data['avatar'] = $res['data'];
      }

      //isUpdate => 是否更新数据
      $result = $this->BusinessModel->isUpdate()->save($data);

      if ($result === false) {
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
          is_file(trim($data['avatar'], '/')) && unlink(trim($data['avatar'], '/'));
        }
        $this->error('修改失败');
      } else {
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
          is_file(trim($businessinfo['avatar'], '/')) && unlink(trim($businessinfo['avatar'], '/'));
        }
        $this->success('修改成功', 'home/business/index');
      }
    }

    $province = $pathlist = $this->RegionModel->where('code', $this->LoginUser['province'])->value('name');

    $city = $pathlist = $this->RegionModel->where('code', $this->LoginUser['city'])->value('name');

    $district = $pathlist = $this->RegionModel->where('code', $this->LoginUser['district'])->value('name');

    $this->assign([
      'province' => $province,
      'city' => $city,
      'district' => $district
    ]);
    return $this->view->fetch();
  }

  // 联系我们
  public function contact()
  {
    $subjectlist = $this->SubjectModel->field('id,title,thumbs')->order('createtime', 'DESC')->limit(5)->select();

    // 获取系统配置信息
    $contact = config('site.contact') ?? '';

    $mobile = config('site.mobile') ?? '';

    $address = config('site.address') ?? '';

    $this->assign([
      'subjectlist' => $subjectlist,
      'contact' => $contact,
      'mobile' => $mobile,
      'address' => $address
    ]);
    return $this->view->fetch();
  }

  // 我的订单
  public function order()
  {
    // $list = [];
    if ($this->request->isAjax()) {
      $page = $this->request->param('page', 1, 'trim');
      $limit = $this->request->param('limit', 10, 'trim');

      // 获取总数
      $count = $this->OrderModel->where('busid', $this->LoginUser['id'])->count();
      // 获取分页数据
      $list = $this->OrderModel->with('subject')->where('busid', $this->LoginUser['id'])->order('createtime', 'DESC')->page($page, $limit)->select();


      /*   $list = $this->OrderModel
      ->alias('o')
      ->join('pre_subject s', "o.subid = s.id")
      ->where('o.busid', $this->LoginUser['id'])
      ->order('createtime', 'DESC')->page($page, $limit)->select();
      */

      $data = [
        'count' => $count,
        'list' => $list
      ];

      if ($list) {
        $this->success('', '', $data);
      } else {
        $this->error();
      }
    }
 /*    $this->assign([
      'status' => 'order',
      'orderlist' => $list
    ]); */
    return $this->view->fetch();
  }
  // 我的订单
  /*   public function order()
  {
    $orderlist = $this->OrderModel->where('busid', $this->LoginUser['id'])->select();
    halt($orderlist);
    $this->assign('orderlist', $orderlist);

    return $this->view->fetch();
  } */



  // 评论
  public function comment()
  {
    $subid = $this->request->param('subid', 0, 'trim');
    $info = $this->SubjectModel->find($subid);

    if (!$info) {
      $this->error('课程不存在');
    }

    if ($this->request->isPost()) {
      $content = $this->request->param('content', '', 'trim');

      $data = [
        'content' => $content,
        'busid' => $this->LoginUser['id'],
        'subid' => $subid,
      ];

      // 添加校验器
      $result = $this->CommentModel->validate('common/Business/Comment')->save($data);
     
      if (!$result) {
        // $this->error('评论失败');
        $this->error($this->CommentModel->getError());
      } else {
        $this->success('评论成功', 'home/business/order');
      }
    }

    $this->assign('info', $info);
    return $this->view->fetch();
  }

  // 消费记录
  public function record()
  {
    // $list = [];
    if ($this->request->isAjax()) {
      $page = $this->request->param('page', 1, 'trim');
      $limit = $this->request->param('limit', 10, 'trim');

      // 获取总数
      $count = $this->RecordModel->where(['busid' => $this->LoginUser['id'], 'state' => '1'])->count();
      // 获取分页数据
      $list = $this->RecordModel->where(['busid' => $this->LoginUser['id'], 'state' => '1'])->order('createtime', 'DESC')->page($page, $limit)->select();
      // $recordlist = $this->RecordModel->where(['busid' => $this->LoginUser['id'], 'state' => '1'])->order('createtime', 'DESC')->select();

      $data = [
        'count' => $count,
        'list' => $list
      ];

      if ($list) {
        $this->success('', '', $data);
      } else {
        $this->error();
      }
    }

  /*   $this->assign([
      'status' => 'record',
      'recordlist' => $list
    ]); */
    return $this->view->fetch();
  }
}
